#!/usr/bin/env python


from __future__ import with_statement
from os import *
import sys
import compiler
import traceback

       
class python_interpreter:
    def run_script(self, src, script='<string>'):
        code = compiler.compile(src, script, 'exec');
        try:
            #exec(code, globals(), locals())
            exec(code, {})
        except Exception, e:
            print "Found Exception: "+ str(e)
            return traceback.format_exc()
        return ""

class ScriptCode(object):
    def __init__(self, name="<string>"):
        self.name = name
        self.code = None
    def code_set(self, code):
        self.code = code
    def run(self):
        python_interpreter().run_script(self.code, script=self.name)
    #TODO
    def load(self):
        pass
    #TODO
    def save(self):
        pass
 

if __name__ == '__main__':
    testcase = '''A=0
for i in xrange(0,100):
    A=A+i
print "ans = " + str(A)
'''
    testcase_bad = '''A = 100*100
print A;
f.read()
'''
    PI = python_interpreter()
    PI.run_script(testcase)
    code = ScriptCode("ScriptCode/Test")
    code.code_set(testcase)
    code.run()
    ret = PI.run_script(testcase_bad, script="bad code")
    print "ret = '" + ret +"'"
